﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain;
using Enyim.Caching;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.API.Application.Commands
{
	/// <summary>
	/// 
	/// </summary>
	public class CheckConsumeCodeCommandHandler : IRequestHandler<CheckConsumeCodeCommand, Zmodel>
	{
		private readonly IUserLogService _userLogService;
		private readonly Casamiel.API.Application.Services.IIcApiService _iicApiService;
        private readonly IMemcachedClient _memcachedClient;
        private readonly string _memcachedPrex;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iicApiService"></param>
        /// <param name="userLogService"></param>
        /// <param name="memcachedClient"></param>
        /// <param name="options"></param>
        public CheckConsumeCodeCommandHandler(IIcApiService iicApiService,IUserLogService userLogService, IMemcachedClient memcachedClient, IOptionsSnapshot<CasamielSettings> options)
		{
            if (options is null) {
                throw new ArgumentNullException(nameof(options));
            }

            _iicApiService = iicApiService;
			_userLogService = userLogService;
            _memcachedClient = memcachedClient;
            _memcachedPrex = options.Value.MemcachedPre;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="request"></param>
		/// <param name="cancellationToken"></param>
		/// <returns></returns>
		public async Task<Zmodel> Handle(CheckConsumeCodeCommand request, CancellationToken cancellationToken)
		{
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var zmodel = await _iicApiService.Icconsumecheck(request.CardNO, request.ConsumeCode,$"{request.Source}099".ToInt32(0)).ConfigureAwait(false);
			var rnt = JsonConvert.DeserializeObject<JObject>(zmodel.content);
			var n = new { code = zmodel.code, content = rnt, msg = zmodel.msg };
			if (rnt != null)
			{
				var je = rnt["money"].ToDecimal(-1);
				if (je > 0 && zmodel.code == 301)
				{
                    var _cachekey = _memcachedPrex + Constant.CONSUMECODE + request.ConsumeCode;

                    var trynum = _memcachedClient.Increment(_cachekey, 1, 1);
                    if (trynum < 2) {
                        var logdata = new UserLog { Url = request.RequestUrl, OPInfo = $"扫码支付,卡号:[{request.CardNO}],支付码[{request.ConsumeCode}]，支付金额{je}", OPTime = DateTime.Now, UserName = request.Mobile, UserIP = request.UserIP };
                        await _userLogService.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                    }
                    
				}
			}
			return zmodel;
		}
	}
}
